package com.vpen.client.matter;

import cn.hutool.json.JSONUtil;
import com.vpen.client.heard.HeardClient;
import com.vpen.common.Matter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.annotation.Resource;


/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/11/25 10:04
 */

@Component
@Slf4j
public class MatterHandler extends AbstractWebSocketHandler {

    @Resource
    @Lazy
    private MatterClient matterClient;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        matterClient.ping();
    }

    /**
     * 接受服务器发回来的pong
     */
    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) {
        log.debug("{}:pong", session.getRemoteAddress());
    }

    /**
     * 接受服务器的文本消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        Matter matter = JSONUtil.toBean(message.getPayload(), Matter.class);
        log.debug("接受到服务器的推送过来的材料:{}", matter);
        log.debug("正在存入数据库....");
    }

    /**
     * 当断开连接后调用
     * 实现断线重连
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.debug("与服务器断开连接，正在尝试重连....:{},{}", session, status);
        matterClient.reconnect();
    }
}
